import React, { ChangeEvent, ChangeEventHandler, useEffect } from "react";
import { Button, message, Popconfirm, Modal, Table } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { getStorageManager } from '@/file_storage'
import { sanitizeFileName, downloadByBlob } from '@/common/utils';
import { parseFromCSV, stringifyToCSV } from '@/common/csv'
import { addLog, listCSV } from '@/actions'
import { readableSize } from '@/common/utils'
import { EyeOutlined, DownloadOutlined, CloseOutlined } from '@ant-design/icons'
import { State } from '@/reducers'
import './index.less'

export type Csv = {
    name: string;
    size: number;
    fullPath: string;
    createTime: Date;
}

export default function CSVList() {

    const dispatch = useDispatch()
    const list = useSelector((state: State) => state.csvs)

    // 保存数组数据到csv
    const saveArray = () => {
        const csvStorage = getStorageManager().getCSVStorage();
        // 将json转化为csV数据
        stringifyToCSV([
            [
                "1",
                "2",
                "3"
            ],
            [
                "a",
                "b",
                "c"
            ],
            [
                "a1",
                "a2",
                "a3"
            ]
        ]).then((stringData: any) => {
            // console.log(stringData, 'stringData')
            csvStorage.write('a.csv', new Blob([stringData]));
        })
    }

    // 读取csv数据到array
    const getArrayData = (fullPath: string) => {
        getStorageManager().getCSVStorage().read(fullPath, 'Text').then((res: any) => {
            // 将csv转化为json
            parseFromCSV(res).then(jsonData => {
                console.log(jsonData, 'jsonData')
            })
        })
    }

    // 上传CSV
    const onFileChange: ChangeEventHandler<HTMLInputElement> = (e: ChangeEvent<HTMLInputElement>) => {
        const csvStorage = getStorageManager().getCSVStorage()
        const files = [].slice.call(e.target.files)
        if (!files || !files.length) return

        const read = (file: File) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = (readerEvent) => {
                    const text = readerEvent.target!.result
                    resolve({
                        text,
                        fileName: file.name
                    })
                }
                reader.readAsText(file)
            })
        }

        Promise.all(files.map(read))
            .then((list: any[]) => {
                const ps = list.map(fileItem => csvStorage.write(sanitizeFileName(fileItem.fileName), new Blob([fileItem.text])))
                return Promise.all(ps).then(() => dispatch(listCSV() as any))
                    .then(() => {
                        message.info(`${list.length} csv files imported`)
                    })
            })
            .catch(e => {

            })
    }

    const removeCSV = (csv: any) => {
        const csvStorage = getStorageManager().getCSVStorage()

        csvStorage.remove(csv.name)
            .then(() => dispatch(listCSV() as any))
            .then(() => {
                message.success(`successfully deleted`)
                dispatch(addLog('info', `${csv.name} deleted`) as any)
            })
    }

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: 'Size',
            dataIndex: 'size',
            key: 'size',
            render: (d: number) => {
                return readableSize(d)
            }
        },
        {
            title: 'Last Modified',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (d: Date) => {
                const pad = (n: number) => n >= 10 ? ('' + n) : ('0' + n)
                return `${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
            }
        },
        {
            title: 'Action',
            key: 'ops',
            width: 110,
            render: (text: string, csv: Csv, index: number) => {
                return (
                    <div>
                        <Button
                            size="small"
                            shape="circle"
                            onClick={(ev) => {
                                ev.preventDefault()
                                // viewCSV(csv)
                                getArrayData(csv.fullPath)
                            }}
                        >
                            <EyeOutlined />
                        </Button>

                        <Button
                            size="small"
                            type="primary"
                            shape="circle"
                            onClick={() => {
                                // downloadCSV(csv)
                                getStorageManager().getCSVStorage().read(csv.fullPath, 'Text').then((text: any) => {
                                    const blob = new Blob([text])
                                    downloadByBlob(blob, csv.name)
                                })
                            }}
                        >
                            <DownloadOutlined />
                        </Button>

                        <Popconfirm
                            title="确认删除？"
                            okText="Delete"
                            onConfirm={() => { removeCSV(csv) }}
                        >
                            <Button
                                size="small"
                                danger
                                shape="circle"
                                onClick={() => {
                                    Modal.confirm({
                                        title: '确认删除？',
                                        onOk: () => {
                                            removeCSV(csv)
                                        }
                                    })
                                }}
                            >
                                <CloseOutlined />
                            </Button>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ]

    const tableConfig = {
        columns,
        dataSource: list,
        pagination: false,
        bordered: true,
        size: 'middle',
        rowKey: 'fullPath',
        rowClassName: () => {
            return ''
        }
    } as any

    // 请求数据
    useEffect(() => {
        dispatch(listCSV() as any)
    }, [])

    return <div className="csv-content">
        {/* <Space>
            <Button className="load-csv-button">
                <label htmlFor="select_csv_files">上传CSV文件</label>
                <input
                    multiple
                    type="file"
                    accept=".csv"
                    id="select_csv_files"
                    onChange={onFileChange}
                    style={{ display: 'none' }}
                />
            </Button>
            <Button onClick={saveArray} >测试保存array</Button>
        </Space> */}
        <Table {...tableConfig} />
    </div>
}